Plex.Lib.JS.load('Data.Jax');
Plex.Lib.JS.load('UI.Widget.Fly_Window');
Plex.Lib.JS.load('UI.Input.Context');

function getAttributes(el)
{
	var atts = el.attributes;
	var realAtts = {};

	for(var i=0; i< atts.length; i++)
	realAtts[atts[i].nodeName]=atts[i].nodeValue;

	return realAtts;
}

function nf_RA()
{
	for ( var i=0; i < arguments.length; i++ )
	{
		var C = arguments[i].childNodes.length;
		for(var j=0;j<C;j++)
		arguments[i].removeChild(arguments[i].childNodes.item(0));
	}
}


function File_Uploader(title,toCategoryId)
{
	var self = this;
	this.window = new Plex.UI.Widget.Fly_Window({
		title:title,
		onclose:function()
		{
			self.onclose();
		}
	});
	this.window.box.settings.moveEffect=false;
	this.el = {};
	this.onclose = function(){}


	this.el.uploader = new Element('embed',{
	'bgcolor':'#CCCCCC',
	'id':'EmbedFlashFilesUpload',
	'src':'/swf/uploader.swf',
	'quality':'high',
	'pluginspage':'http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash',
	'type':'application/x-shockwave-flash',
	'width':'500',
	'height':'350',
	'flashvars':'uploadUrl=/handlers/Upload/multiUploader.php' + (toCategoryId ? '?file_category_ID=' + toCategoryId : '')
	})



	this.open = function()
	{
		if(!self.initialized)
		this.init();

		self.window.open(500,350);
	}

	this.close = function()
	{
		self.window.close();
	}

	this.init = function()
	{
		self.el.uploader.injectInside(self.window.body);
	}
}

Plex.Util.File_Selector = function (title)
{
	var self = this;
	this.window = new  Plex.UI.Widget.Fly_Window({title:title?title:'File Selector'});
	this.Jax = new Plex.Data.Jax();
	this.initialized = false;
	this.folder = [];
	this.currentFolder = false;
	this.onselect = function(id){};

	// ** ////////////// ** //
	// ** // ELEMENTS // ** //
	// ** ////////////// ** //

	this.element = {};

	this.element.table = new Element('table',{
	'cellspacing':0,
	'cellpadding':0,
	'border':0,
	'class':'yellow',
	'styles':{
		'width':900
	}
	})

	this.element.mainRow = new Element('tr').injectInside(self.element.table);

	this.element.leftCol = new Element('td',{
	'valign':'top',
	'width':'30%'
	}).injectInside(self.element.mainRow);


	this.element.rightCol = new Element('td',{
	'valign':'top',
	'width':'70%'
	}).injectInside(self.element.mainRow);

	//Tree Nav
	this.element.leftTable = new Element('table',{
	'cellpadding':0,
	'cellspacing':0,
	'styles': {
	'width':'100%',
	'border':'0px',
	}
	}).injectInside(self.element.leftCol);

	this.element.leftHeaderRow = new Element('tr').injectInside(self.element.leftTable);

	this.element.leftHeader = new Element('td',{
	'class':'cat'
	}).setText('Folders').injectInside(self.element.leftHeaderRow);

	this.element.leftTreeRow = new Element('tr').injectInside(self.element.leftTable);
	this.element.leftTreeCol = new Element('td',{
	'valign':'top',
	'styles':{
	'border-color':'#707070 rgb(0, 0, 0) rgb(0, 0, 0) rgb(112, 112, 112)',
	'border-style':'solid',
	'border-width':'1px',
	'background-color':'#414141',
	'height':'600px',
	}
	}).injectInside(self.element.leftTreeRow);

	this.element.leftTree = new Element('div',{
	'styles':{
	'height':'600px',
	'overflow':'auto'
	}
	}).injectInside(self.element.leftTreeCol);

	this.element.leftTreeTbl = new Element('table').injectInside(this.element.leftTree);


	//Right Button Nav
	this.element.rightTable = new Element('table',{
	'cellpadding':0,
	'cellspacing':0,
	'styles': {
	'width':'100%',
	'border':'0px',
	}
	}).injectInside(self.element.rightCol);

	this.element.rightHeaderRow = new Element('tr').injectInside(self.element.rightTable);

	this.element.rightHeader = new Element('td',{
	'class':'cat',
	'align':'right',
	'valign':'middle',
	'styles':{
	'vertical-align':'middle'
	}
	}).injectInside(self.element.rightHeaderRow);

	this.element.uploadImage = new Element('a', {
	'href':'#',
	'styles':{
	'padding-top':'5px',
	'padding-left':'5px',
	'float':'left'
	},
	'events':{
	'click':function()
	{
		if(!self.currentFolder)
		{
			alert("Please Choose Which Category To Add A New File Into");
		}
		else
		{
			var iu = new File_Uploader("Upload Files Into " + self.currentFolder.name,self.currentFolder.id);
			iu.onclose = function()
			{
				self.openFolder(self.currentFolder.id,true);
			}
			iu.open();
		}
	}
	}
	}).setText('Upload File').injectInside(self.element.rightHeader)


	this.element.searchTbl =  new Element('table',{
	'cellpadding':2,
	'cellspacing':1,
	'styles': {
	'border':'0px',
	'background-color':'transparent',
	'float':'right'
	}
	}).injectInside(self.element.rightHeader);

	this.element.searchRow = new Element('tr').injectInside(self.element.searchTbl);

	//	this.element.searchTitle = new Element('td').setText('Image Name').injectInside(self.element.searchRow);
	this.element.searchInputCol = new Element('td').injectInside(self.element.searchRow);
	this.element.searchButtonCol = new Element('td').injectInside(self.element.searchRow);

	this.element.searchButton = new Element('input',{
	'type':'text',
	'class':'post',
	'styles': {
	'margin-right':5
	}
	}).injectInside(self.element.searchButtonCol);

	this.element.searchButton = new Element('input',{
	'type':'button',
	'class':'button',
	'value':'Search Images'
	}).injectInside(self.element.searchButtonCol);



	this.element.rightBodyRow = new Element('tr').injectInside(self.element.rightTable);

	this.element.rightBodyTd = new Element('td',{
	'valign':'top',
	'events':{

	},
	'styles':{
	'border-color':'#707070 rgb(0, 0, 0) rgb(0, 0, 0) rgb(112, 112, 112)',
	'border-style':'solid',
	'border-width':'1px',
	'background-color':'#414141',
	'height':'600px',
	}

	}).injectInside(self.element.rightBodyRow);

	this.element.rightBodyCol = new Element('div',{
	'styles':{
	'height':'600px',
	'width':'600px',
	'overflow':'auto'
	}
	}).injectInside(self.element.rightBodyTd);


	this.contextMenu = new Plex.UI.Input.Context(this.element.rightBodyCol);
	this.contextMenu.addOption('Create Folder',function(){
		self.createFolder(self.currentFolder.id);
	});
	//	this.contextMenu.addOption('Move File',function(){
	//		alert('File Moved');
	//	})

	var treeFolder = function(id,name)
	{
		var folder = {};
		folder.expanded=false;
		folder.loaded=false;
		folder.height=0;
		folder.id = id;
		folder.name = name;
		folder.nameRow = new Element('tr',{});
		folder.iconCol = new Element('td',{'width':9}).injectInside(folder.nameRow);
		folder.nameCol = new Element('td',{
		'valign':'middle',
		'styles':{
		'cursor':'pointer',
		'color':'#E7E7E7'
		},
		'events':{
		'click':function(){
			self.openFolder(id);
		}
		}
		}).setText(name).injectInside(folder.nameRow);

		folder.icon = new Element('img',{
		'width':9,
		'src':'/img/Fly_Box/plus.gif',
		'styles':{
		'cursor':'pointer'
		},
		'events':{
		'click':function()
		{
			folder.expandTree();
		}
		}
		}).injectInside(folder.iconCol);

		folder.icons = new Element('div',{});

		folder.kidsRow = new Element('tr',{});
		folder.kidsCol = new Element('td',{'colspan':2}).injectInside(folder.kidsRow);
		folder.kidsDiv = new Element('div',{'styles':{'height':0,'opacity':0}}).injectInside(folder.kidsCol);
		folder.kidsTbl = new Element('table',{'styles':{'margin-left':'8px'}}).injectInside(folder.kidsDiv);

		folder.moveTo = function(parent)
		{
			parent.adopt([folder.nameRow,folder.kidsRow]);
		}

		folder.contextMenu = new Plex.UI.Input.Context(folder.nameCol)
		folder.contextMenu.addOption('New Sub Folder',function(){self.createFolder(folder.id);});
		folder.contextMenu.addOption('Rename Folder',function(){
			var folderName = prompt("Rename Folder To");

			if(!folderName)
			return false;

			var QJax = new Plex.Data.Jax();
			QJax.feed = 'File_Category';
			QJax.action = 'Update';
			QJax.Var('file_category_ID',folder.id)
			QJax.Var('category_name',folderName);
			QJax.handler=function(response)
			{
				folder.nameCol.setText(folderName);
				folder.name = folderName;
			}
			QJax.Call();
		});
		folder.contextMenu.addOption('Refresh Folder',function(){self.createFolder(folder.id);});
		folder.contextMenu.addOption('Remove Folder',function()
		{
			Plex.Lib.JS.load("UI.Widget.Fly_Option");
			var optionBox = new Plex.UI.Widget.Fly_Option({
				title:'Are You Sure You Want To Delete ' + folder.name +'?',
				options:
				[
				{
				'text':'Yes, Delete This Folder',
				'onclick':function(){
					var QJax = new Plex.Data.Jax();
					QJax.feed = 'File_Category';
					QJax.action = 'Update';
					QJax.Var('file_category_ID',folder.id)
					QJax.Var('row_status_ID',3);
					QJax.handler=function(response)
					{

						if(folder.nameRow.parentNode && folder.kidsRow.parentNode)
						{
							var nameFx = new Fx.Styles(folder.nameRow,{duration:500,wait:false,transition: Fx.Transitions.Quad.easeOut});
							var kidsFx = new Fx.Styles(folder.kidsRow,{duration:500,wait:false,transition: Fx.Transitions.Quad.easeOut});

							kidsFx.start({
							'opacity':[1,0]
							}).chain(function(){
								folder.kidsRow.style.height = folder.kidsRow.offsetHeight;
								folder.kidsRow.empty();
								kidsFx.start({
								'height':0
								}).chain(function(){
									folder.kidsRow.parentNode.removeChild(folder.kidsRow);

								})
							})

							nameFx.start({
							'opacity':[1,0]
							}).chain(function(){
								folder.nameRow.style.height = folder.nameRow.offsetHeight;
								folder.nameRow.empty();
								nameFx.start({
								'height':0
								}).chain(function(){
									folder.nameRow.parentNode.removeChild(folder.nameRow);
								})
							})

						}

					}
					QJax.Call();
					this.close();
				}
				},
				{
				'text':"No, Don't Delete",
				'onclick':function(){
					this.close();
				}
				}
				]
			});

			optionBox.open();
		});

		folder.fx = new Fx.Styles(folder.kidsDiv, {
			duration: 500,
			wait: false,
			transition: Fx.Transitions.Quad.easeOut
		});


		folder.expandTree = function(after)
		{
			if(folder.expanded)
			{
				if(folder.height==0)
				folder.height = folder.kidsDiv.offsetHeight;

				folder.fx.start({
				'opacity':[1,0],
				'height': [folder.height,0]
				}).chain(function(){
					folder.kidsDiv.style.display='none'
				})

				folder.icon.src='/img/Fly_Box/plus.gif';
				folder.expanded=false;
			}
			else
			{
				if(!folder.loaded)
				{
					if(after)
					self.expandTree(id,after);
					else
					self.expandTree(id);

					folder.loaded=true;
				}
				else
				{
					folder.kidsDiv.style.display='';
					folder.fx.start({
					'opacity':[0,1],
					'height': [0,folder.kidsTbl.scrollHeight]
					}).chain(function(){
						folder.kidsDiv.style.height='';
					});
				}

				folder.icon.src='/img/Fly_Box/minus.gif';
				folder.expanded=true;
			}
		}

		self.folder[id]=folder;

		return folder;
	}

	var iconButton = function()
	{
		var icon = {
			el:{},
			onclick : function(){},
		};

		icon.el.div = new Element('div',{
		'styles':
		{
		'float':'left',
		'width':'275px',
		'height':'76px',
		'color':"#E7E7E7"
		}
		})

		icon.el.mainTable = new Element('table',{
		'styles': {
		'cursor':'default',
		'width':'100%',
		'border':'2px solid transparent'
		},
		'events': {
		'mouseover': function(e)
		{
			this.style.border='2px groove grey'
			this.style.backgroundColor='#555555';
		},
		'mouseout': function(e)
		{
			this.style.border='2px solid transparent'
			this.style.backgroundColor='';
		},
		'click':function(e)
		{
			icon.onclick();
		}
		}
		}).injectInside(icon.el.div);

		icon.el.mainRow = new Element('tr').injectInside(icon.el.mainTable);
		icon.el.leftCol = new Element('td',{'styles':{'width':'70px','text-align':'center','vertical-align':'middle'}}).injectInside(icon.el.mainRow);
		icon.el.rightCol = new Element('td',{'styles':{
		'text-align':'left',
		'vertical-align':'middle'
		}}).injectInside(icon.el.mainRow);
		icon.el.icon = new Element('img',{
		'src':'/img/homebrew/blue/70/folder.png',
		'styles':{
		'max-width':70,
		'max-height':70
		}
		}).injectInside(icon.el.leftCol);
		icon.el.rightTable = new Element('table').injectInside(icon.el.rightCol);


		icon.el.titleRow = new Element('tr').injectInside(icon.el.rightTable);
		icon.el.titleCol = new Element('td',{'styles':{'text-align':'left','font-weight':'900',}}).injectInside(icon.el.titleRow);

		icon.setTitle = function(title)
		{
			if(title.length>20)
			title = title.substr(0,20)+'...';

			icon.el.titleCol.setText(title);
		}

		icon.setImage = function(src)
		{
			icon.el.icon.src = src;
		}

		icon.addDetails = function(txt)
		{
			var detailsRow = new Element('tr').injectInside(icon.el.rightTable);
			var detailsCol = new Element('td',{'styles':{'text-align':'left','color':'#bbbbbb'}}).setText(txt).injectInside(detailsRow);
		}

		icon.moveTo = function(par)
		{
			icon.el.div.injectInside(par);
		}

		return icon;
	}

	var iconFolder = function(info)
	{
		var button = new iconButton()
		button.onclick = function()
		{
			if(self.folder[info.file_category_ID])
			{
				if(!self.folder[info.parent_file_category_ID].expanded)
				self.folder[info.parent_file_category_ID].expandTree();

				self.openFolder(info.file_category_ID);
			}
			else
			{
				self.folder[info.parent_file_category_ID].expandTree(info.file_category_ID);
			}
		}

		button.setTitle(info.category_name);







		button.setImage('/img/areo2/70/Folder.png');

		return button;
	}

	var fileIcon = function(info)
	{
		var button = new iconButton()
		button.el.mainTable.onclick = function(ev)
		{
			self.onselect(info)
		}

		button.setTitle(info.file_name);


		file_type_icons = new Array();


		if(info.file_type_ID==21 || info.file_type_ID==22 || info.file_type_ID==18)
		{//Image FIles

			button.addDetails(info.file_type);
			button.addDetails(info.width + 'x' + info.height);
			button.setImage('/img/aloader.gif');

			var tmpImage = new Image();
			tmpImage.src = Plex.Com.Image.getURL(info.file_content_ID,70,70);
//			console.log(tmpImage.src);
			tmpImage.onload = function()
			{
				button.el.icon.src=tmpImage.src;
			}

		}
		else if(info.file_type_ID==17)
		{//Video Files
			button.addDetails(info.file_type);
			button.addDetails(info.width + 'x' + info.height);
			button.setImage('/img/areo2/70/AVI.png');
		}
		else if(info.file_type_ID==19)
		{//Audio Files
			button.addDetails(info.file_type);
			button.addDetails(self.formatTime(info.length));
			button.setImage('/img/areo2/70/MP3.png');
		}
		else if(info.file_type_ID==20)
		{//Audio Files
			button.addDetails(info.file_type);
			button.addDetails(self.formatTime(info.length));
			button.setImage('/img/areo2/70/SWF.png');
		}
		else
		button.setImage('/img/homebrew/blue/70/document.png');

		button.contextMenu = new Plex.UI.Input.Context(button.el.mainTable)
		button.contextMenu.addOption('Delete Image',function()
		{
			var QJax = new Plex.Data.Jax();
			QJax.feed = 'File_Content';
			QJax.action = 'Update';
			QJax.Var('file_content_ID',info.file_content_ID)
			QJax.Var('row_status_ID',3);
			QJax.handler=function(response)
			{
				button.el.div.remove();
			}
			QJax.Call();
		});

		return button;
	}

	this.createFolder = function(id)
	{
		var folderName = prompt("New Folder Name");

		if(!folderName)
		return false;

		var QJax = new Plex.Data.Jax();
		QJax.feed = 'File_Category';
		QJax.action = 'Add';
		QJax.Var('parent_file_category_ID',id)
		QJax.Var('category_name',folderName);
		QJax.handler=function(response)
		{
			self.openFolder(self.currentFolder.id,true);
		}
		QJax.Call();
	}

	this.openFolder = function(id,refresh)
	{
		if(self.currentFolder == self.folder[id] && !refresh)
		return true;
		else if(self.currentFolder!==false)
		{
			self.currentFolder.nameCol.style.backgroundColor='';
		}

		self.Jax.feed = 'File_Category';
		self.Jax.action = 'Search';
		self.Jax.Var('parent_file_category_ID',id)

		self.Jax.handler=function(response)
		{
			var results = response.getElementsByTagName('results').item(0).childNodes;

			var parentFolder = self.folder[id].icons;
			nf_RA(parentFolder)


			for(var i=0; i<results.length; i++)
			{
				var result = getAttributes(results[i]);
				var iconF = new iconFolder(result);
				iconF.moveTo(parentFolder)
			}

			var QJax = new Plex.Data.Jax();
			QJax.feed = 'File_Content';
			QJax.action = 'Search';
			QJax.Var('file_category_ID',id)
			QJax.Var('row_status_ID',1);
			QJax.Var('order_by','file_name');
			QJax.handler=function(response)
			{
				var results = response.getElementsByTagName('results').item(0).childNodes;
				for(var i=0; i<results.length; i++)
				{
					var result = getAttributes(results[i]);
					var iconF = new fileIcon(result);
					iconF.moveTo(parentFolder)
				}
			}
			QJax.Call();

			nf_RA(self.element.rightBodyCol)

			self.element.rightBodyCol.setHTML('&nbsp;');
			parentFolder.injectInside(self.element.rightBodyCol);

			self.currentFolder = self.folder[id];
			self.currentFolder.nameCol.style.backgroundColor='#555555';

		}

		self.Jax.Call();

	}

	this.expandTree = function(id,openAfter)
	{
		self.Jax.feed = 'File_Category';
		self.Jax.action = 'Search';
		self.Jax.Var('order_by','category_name')
		self.Jax.Var('parent_file_category_ID',id?id:'0')

		self.Jax.handler=function(response)
		{
			var results = response.getElementsByTagName('results').item(0).childNodes;
			

			for(var i=0; i<results.length; i++)
			{
				var result = getAttributes(results[i]);

				var tf = new treeFolder(result.file_category_ID,result.category_name);

//				console.log(tf);
				
				if(result.parent_file_category_ID=='')
				tf.moveTo(self.element.leftTreeTbl)
				else
				tf.moveTo(self.folder[result.parent_file_category_ID].kidsTbl)

			}

			if(id && id!='0')
			{
				self.folder[id].fx.start({
				'opacity':[0,1],
				'height': [0,self.folder[id].kidsTbl.scrollHeight]
				}).chain(function(){
					self.folder[id].kidsDiv.style.height='';
				});
			}
			else
			self.initialized = true;

			if(openAfter)
			self.openFolder(openAfter);
		}

		self.Jax.Call();
	}

	this.formatTime = function (seconds)
	{
		seconds = Math.ceil(seconds);

		var minutes = hours = 0;

		if(seconds>=60)
		{
			minutes = Math.floor(seconds/60);
			seconds -= minutes*60;
		}

		if(minutes>=60)
		{
			hours = Math.floor(minutes/60);
			minutes -= hours*60;
		}

		strSeconds = seconds<10 ? "0"+seconds : seconds;
		strMinutes = minutes<10 ? "0"+minutes : minutes;
		strHours = hours<10 ? "0"+hours : hours;

		if(hours>0)
		return strHours+":"+strMinutes+":"+strSeconds;
		else
		return strMinutes+":"+strSeconds;
	}

	this.open = function()
	{
		if(!self.initialized)
		this.init();

		self.window.open(900,600);
	}

	this.close = function()
	{
		self.window.close();
	}

	this.init = function()
	{
		self.element.table.injectInside(self.window.body);
		self.expandTree('0');
	}
}
